import sys
sys.path.insert(-1, "..")
from utils.http_utils import *
from utils.cv2_utils import get_image_from_url

class YJAPI:
    def __init__(self, cookie=None):
        self.cookie = cookie or "yx_sid=eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjM2NzQzODgwMTksInBob25lIjoiMTg2ODg4NTk4ODYiLCJzY2hvb2xOYW1lIjoi5rWL6K-V5a2m5qChMDAwMiIsIm5hbWUiOiLmloflsI_nqboiLCJqdGkiOiIxOTEzMTc0MzI4NzU0MTc2Iiwic2Nob29sSWQiOjM4NDEwM30.ikN7XRTrWc3nV51Pnv71NQlpA1fzgw_Jpf-uBBkiK_pN9JDof3PKdQ3WjzJSG5UgtS-QiLkwbmQN4g3QkBEV_g"

    def fetch_template_data(self, subject_id):
        """获取模板数据
        
        Args:
            subject_id (str): 题目ID
            
        Returns:
            list: 图片文件列表
        """
        try:
            headers = {
                'cookie': self.cookie
            }

            url = 'https://grayyue.haofenshu.com/filter/yue/v353/template/query'
            params = {
                'subjectId': subject_id
            }

            response = get_request(url, headers=headers, params=params)
            if response is None or 'data' not in response.json():
                return None
            
            template_data = response.json()['data'][0]
            if template_data is None or 'files' not in template_data.keys():
                print("Error: Data format is different from expected.")
                return None

            return template_data['files']
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            return None
        
    def fetch_exam_paper_data(self, subject_id):
        """获取原卷数据
        
        Args:
            subject_id (str): 题目ID
            
        Returns:
            list: 图片文件列表
        """
        try:
            headers = {
                'cookie': self.cookie
            }

            url = 'http://gray-yj-api.haofenshu.com/v353/subject/info'
            params = {
                'subjectId': subject_id,
                "options": ["origin_paper"]
            }

            response = post_request(url, headers=headers, json=params)
            if response is None or 'data' not in response.json():
                return None
            
            template_data = response.json()['data']["origin_paper"]
            # print("response data : ", template_data)
            # res = 'files' not in template_data
            # print("res : ", res)
            if template_data is None or 'files' not in template_data:
                print("Error: Data format is different from expected.")
                return None

            return template_data['files']
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            return None
    
    def transform_image_file_to_url(self, image_file):
        """转换图片文件为可下载的URL
        
        Args:
            image_file (str): 图片文件
            
        Returns:
            str: 图片URL
        """
        url = 'https://gray-yj-api.haofenshu.com/v353/image/urls'
        params = {
            'images': image_file
        }

        response = post_request(url, json=params)
        if response is None:
            return None
        return response.json()['data']

    def get_image_urls(self, subject_id):
        """获取图片URL列表
        
        Args:
            subject_id (str): 题目ID
            
        Returns:
            list: 图片URL列表
        """
        image_files = self.fetch_template_data(subject_id)
        if not image_files:
            return None
            
        return self.transform_image_file_to_url(image_files)

    def get_exam_paper_image_urls(self, subject_id):
        """获取图片URL列表
        
        Args:
            subject_id (str): 题目ID
            
        Returns:
            list: 图片URL列表
        """
        image_files = self.fetch_exam_paper_data(subject_id)
        if not image_files:
            return None
            
        return self.transform_image_file_to_url(image_files)

# 测试代码
if __name__ == "__main__":
    yj_api = YJAPI()
    subject_id = 9363031
    # image_urls = yj_api.get_image_urls(subject_id)
    # print("Image URLs:", image_urls)

    image_urls = yj_api.get_exam_paper_image_urls(subject_id)
    print("Image URLs:", image_urls)
